package com.dzt.androidframework.network.mobapi.lottery;

import android.content.Intent;

import com.dzt.androidframework.network.MvpPresenter;
import com.dzt.androidframework.network.MvpView;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by M02323 on 2017/12/7.
 */

public class LotteryPresenter implements MvpPresenter {
	private static final String KEY = "2144415f81930";
	private LotteryManager manager;
	private CompositeSubscription compositeSubscription;
	private LotteryView lotteryView;
	private Lottery lottery;
	private LotteryType lotteryType;

	@Override
	public void onCreate() {
		manager = new LotteryManager();
		compositeSubscription = new CompositeSubscription();
	}

	@Override
	public void onStart() {

	}

	@Override
	public void onStop() {

	}

	@Override
	public void onDestroy() {
		if (compositeSubscription.hasSubscriptions()) {
			compositeSubscription.unsubscribe();
		}
	}

	@Override
	public void attachView(MvpView view) {
		lotteryView = (LotteryView) view;
	}

	@Override
	public void attachIncomingIntent(Intent intent) {

	}

	public void queryLottery(String name) {
		compositeSubscription.add(manager.queryLottery(KEY, name)
				.subscribeOn(Schedulers.io())
				.observeOn(AndroidSchedulers.mainThread())
				.subscribe(new Observer<Lottery>() {
					@Override
					public void onCompleted() {
						if (lottery != null) {
							lotteryView.onSuccess(lottery);
						}
					}

					@Override
					public void onError(Throwable e) {
						lotteryView.onError("请求失败");
					}

					@Override
					public void onNext(Lottery lottery) {
						LotteryPresenter.this.lottery = lottery;
					}
				}));
	}

	public void queryLotteryList() {
		compositeSubscription.add(manager.queryLotteryList(KEY)
				.subscribeOn(Schedulers.io())
				.observeOn(AndroidSchedulers.mainThread())
				.subscribe(new Observer<LotteryType>() {
					@Override
					public void onCompleted() {
						if (lotteryType != null) {
							lotteryView.onSuccess(lotteryType);
						}
					}

					@Override
					public void onError(Throwable e) {
						lotteryView.onError("请求失败");
					}

					@Override
					public void onNext(LotteryType lotteryType) {
						LotteryPresenter.this.lotteryType = lotteryType;
					}
				}));
	}
}
